import com.lsh.domain.Article;

/**
 * @author Administrator
 * @date 2019/11/30 19:04
 */
public class Arithmetic {

    private int[] array;

    public Arithmetic(int[] array) {
        this.array = array;
    }

    // 冒泡排序
    public void bubbleSort(){
        for(int i=0;i<array.length;i++){
            int length = array.length - i;
            for(int j=0;j<length;j++){
                if(j+1 != length){
                    if(array[j] > array[j+1]){
                        int temp = array[j];
                        array[j] = array[j+1];
                        array[j+1] = temp;
                    }
                }
            }
        }
    }

    // 选择排序
    public void selectionSort(){
        for(int i=0;i<array.length;i++){
            int minIndex = i;
            for(int j=i;j<array.length;j++){
                if(array[minIndex] > array[j]) {
                    minIndex = j;
                }
            }
            if(minIndex != i) {
                int temp = array[i];
                array[i] = array[minIndex];
                array[minIndex] = temp;
            }
        }
    }

    // 插入排序
    public void insertSort(){
        int i, j, temp;
        for(i=1;i<array.length;i++){
            temp = array[i];
            for(j=i-1;j >=0;j++){
                if(temp < array[j]){
                    array[j+1] = array[j];
                }else{
                    break;
                }
            }
            array[j+1] = temp;
        }
    }

    // 归并排序
    public void mergerSort(){

    }

    // 二分查找法
    public int binarySearch(int key){
        int low = 0;
        int high = array.length - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(array[mid] == key){
                return mid;
            }else if(array[mid] > key){
                high = mid -1;
            }else if(array[mid] < key){
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {

        int[] array = new int[]{10,7,12,34,1,6,8,11,4,3,15,5,40,2};
        System.out.print("\n冒泡排序：");
        Arithmetic arithmetic1 = new Arithmetic(array);
        arithmetic1.bubbleSort();
        for(int a: array) System.out.print(a + " ");
        System.out.print("\n选择排序：");
        Arithmetic arithmetic2 = new Arithmetic(array);
        arithmetic2.selectionSort();
        for(int a: array) System.out.print(a + " ");
        System.out.print("\n插入排序：");
        Arithmetic arithmetic3 = new Arithmetic(array);
        arithmetic3.insertSort();
        for(int a: array) System.out.print(a + " ");
        System.out.print("\n二分查找法：");
        Arithmetic arithmetic4 = new Arithmetic(array);
        int index = arithmetic4.binarySearch(12);
        System.out.println("index>>>" + index);
    }
}
